import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:merchants/models/attr_name.dart';
import 'package:merchants/providers/providers.dart';
import 'package:merchants/screens/attr_value/attr_value_management_page.dart';

class AttrManagementPage extends ConsumerStatefulWidget {
  const AttrManagementPage({super.key});

  @override
  ConsumerState<AttrManagementPage> createState() => _AttrManagementPageState();
}

class _AttrManagementPageState extends ConsumerState<AttrManagementPage> {
  late Future<List<AttrName>> _attrNamesFuture;
  bool isAdding = false;
  bool isEditing = false;
  int? editingIndex;
  final TextEditingController _nameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    print('DEBUG: AttrManagementPage initState 被调用');
    _attrNamesFuture = ref.read(attrNameServiceProvider).getList();
    print('DEBUG: 规格数据请求已发起');
  }

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }

  void _refreshAttrNames() {
    setState(() {
      _attrNamesFuture = ref.read(attrNameServiceProvider).getList();
      _nameController.clear();
    });
  }

  void _startAdding() {
    print('DEBUG: 添加规格按钮被点击');
    setState(() {
      isAdding = true;
      _nameController.clear();
    });
    print('DEBUG: isAdding 设置为 true');
  }

  void _startEditing(int index, List<AttrName> attrNames) {
    setState(() {
      isEditing = true;
      editingIndex = index;
      _nameController.text = attrNames[index].name;
    });
  }

  Future<void> _confirmDelete(int index, List<AttrName> attrNames) async {
    final attrName = attrNames[index];
    final bool? confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除规格 "${attrName.name}" 吗？\n删除规格将同时删除其下的所有规格值。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('确定'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      await _deleteAttrName(index, attrNames);
    }
  }

  Future<void> _deleteAttrName(int index, List<AttrName> attrNames) async {
    try {
      final attrNameToDelete = attrNames[index];
      await ref
          .read(attrNameServiceProvider)
          .deleteAttrName(attrNameToDelete.id!);
      _refreshAttrNames();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('删除成功'),
            backgroundColor: Colors.green,
            duration: Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('删除失败：$e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  Future<void> _saveEdit(List<AttrName> attrNames) async {
    final newName = _nameController.text.trim();
    print('DEBUG: 保存编辑，newName: "$newName", isAdding: $isAdding');
    
    if (newName.isEmpty || newName.length > 10) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(newName.isEmpty ? '名称不能为空！' : '名称不能超过10个字！')),
      );
      return;
    }

    try {
      if (isAdding) {
        print('DEBUG: 创建新规格');
        await ref
            .read(attrNameServiceProvider)
            .createAttrName(newName);
        _refreshAttrNames();
      } else {
        final attrNameToUpdate = attrNames[editingIndex!];
        print('DEBUG: 更新规格，id: ${attrNameToUpdate.id}, oldName: ${attrNameToUpdate.name}, newName: $newName');
        await ref.read(attrNameServiceProvider).updateAttrName(
          attrNameToUpdate.id!,
          newName,
        );
        _refreshAttrNames();
      }
      setState(() {
        isEditing = false;
        editingIndex = null;
        isAdding = false;
        _nameController.clear();
      });
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('保存失败：$e'), backgroundColor: Colors.red),
      );
    }
  }

  void _cancelEdit() {
    setState(() {
      isAdding = false;
      isEditing = false;
      editingIndex = null;
      _nameController.clear();
    });
  }

  void _navigateToAttrValues(AttrName attrName) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => AttrValueManagementPage(attrName: attrName),
      ),
    ).then((_) {
      // 返回时刷新数据
      _refreshAttrNames();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
          tooltip: '返回',
        ),
        title: const Text('规格管理'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _refreshAttrNames,
            tooltip: '刷新',
          ),
        ],
      ),
      bottomNavigationBar: isAdding || isEditing
          ? null
          : Container(
              padding: const EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: Theme.of(context).scaffoldBackgroundColor,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 4,
                    offset: const Offset(0, -2),
                  ),
                ],
              ),
              child: SafeArea(
                child: SizedBox(
                  width: double.infinity,
                  child: ElevatedButton.icon(
                    onPressed: () {
                      print('DEBUG: 添加规格按钮被点击');
                      if (!isEditing) {
                        _startAdding();
                      }
                    },
                    icon: const Icon(Icons.add),
                    label: const Text('添加规格'),
                    style: ElevatedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                  ),
                ),
              ),
            ),
      body: FutureBuilder<List<AttrName>>(
        future: _attrNamesFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            print('DEBUG: 规格数据加载失败: ${snapshot.error}');
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('加载失败: ${snapshot.error}'),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: _refreshAttrNames,
                    child: const Text('重试'),
                  ),
                ],
              ),
            );
          }

          final attrNames = snapshot.data ?? [];
          print('DEBUG: 获取到 ${attrNames.length} 个规格');

          if (attrNames.isEmpty && !isAdding) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.label_outline,
                    size: 64,
                    color: Colors.grey[400],
                  ),
                  const SizedBox(height: 16),
                  Text(
                    '暂无规格数据',
                    style: TextStyle(
                      fontSize: 18,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 8),
                                          Text(
                          '点击右下角"+"按钮或"生成测试数据"来创建规格',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey[500],
                          ),
                        ),
                ],
              ),
            );
          }

          print('DEBUG: 构建ListView, isAdding: $isAdding, attrNames.length: ${attrNames.length}');
          return Padding(
            padding: EdgeInsets.only(
              bottom: MediaQuery.of(context).padding.bottom + 80, // 为FAB留出空间
            ),
            child: ListView.builder(
              itemCount: isAdding ? attrNames.length + 1 : attrNames.length,
              itemBuilder: (context, index) {
                print('DEBUG: 构建item $index');
                if (isAdding && index == 0) {
                  return ListTile(
                    title: TextField(
                      controller: _nameController,
                      decoration: const InputDecoration(
                        hintText: '请输入规格名称',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    trailing: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        IconButton(
                          icon: const Icon(Icons.save),
                          onPressed: () => _saveEdit(attrNames),
                        ),
                        IconButton(
                          icon: const Icon(Icons.cancel),
                          onPressed: _cancelEdit,
                        ),
                      ],
                    ),
                  );
                }

                final attrNameIndex = isAdding ? index - 1 : index;
                final attrName = attrNames[attrNameIndex];

                return ListTile(
                  leading: Icon(
                    Icons.label,
                    color: Theme.of(context).primaryColor,
                  ),
                  title: isEditing && editingIndex == attrNameIndex
                      ? TextField(
                          controller: _nameController,
                          decoration: const InputDecoration(
                            hintText: '请输入规格名称',
                            border: OutlineInputBorder(),
                          ),
                        )
                      : Text(attrName.name),
                  subtitle: Text('点击管理规格值'),
                  trailing: isEditing && editingIndex == attrNameIndex
                      ? Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            IconButton(
                              icon: const Icon(Icons.save),
                              onPressed: () => _saveEdit(attrNames),
                            ),
                            IconButton(
                              icon: const Icon(Icons.cancel),
                              onPressed: _cancelEdit,
                            ),
                          ],
                        )
                      : Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            IconButton(
                              icon: const Icon(Icons.list),
                              onPressed: () => _navigateToAttrValues(attrName),
                              tooltip: '管理规格值',
                            ),
                            IconButton(
                              icon: const Icon(Icons.delete),
                              onPressed: () => _confirmDelete(attrNameIndex, attrNames),
                              tooltip: '删除',
                            ),
                            IconButton(
                              icon: const Icon(Icons.edit),
                              onPressed: () => _startEditing(attrNameIndex, attrNames),
                              tooltip: '编辑',
                            ),
                          ],
                        ),
                  onTap: () => _navigateToAttrValues(attrName),
                );
              },
            ),
          );
        },
      ),
    );
  }
} 